<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>品牌型号管理</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- <link rel="stylesheet" href="../web/resource/css/allcss/allCss.css" type="text/css"> -->
</head>
<body>
<div class="query-container">
  <div class="form-row">
    <!-- 品牌搜索 -->
    <div class="form-item">
      <label class="form-label">品牌：</label>
      <input type="text" class="form-input" placeholder="请输入品牌名称">
    </div>
    <!-- 型号搜索 -->
    <div class="form-item">
      <label class="form-label">型号：</label>
      <input type="text" class="form-input" placeholder="请输入型号">
    </div>
    <!-- 是否新能源 -->
    <div class="form-item">
      <label class="form-label">是否新能源：</label>
      <select class="form-input form-select-energy form-select">
        <option value="">全部</option>
        <option value="1">是</option>
        <option value="0">否</option>
      </select>
    </div>
    <!-- 状态选择 -->
    <div class="form-item">
      <label class="form-label">状态：</label>
      <select class="form-input form-select-status form-select">
        <option value="">全部</option>
        <option value="1">启用中</option>
        <option value="0">停用</option>
      </select>
    </div>
  </div>
  <!-- 操作按钮 -->
  <div class="action-buttons">
    <button class="btn btn-reset">重置</button>
    <button class="btn btn-query">查询</button>
    <button class="btn btn-add">新增</button>
  </div>
</div>
<div class="table-container">
  <table class="data-table">
    <thead>
    <tr>
      <th>序号</th>
      <th>品牌名称</th>
      <th>型号名称</th>
      <th>配置</th>
      <th>重量</th>
      <th>长x宽x高</th>
      <th>是否新能源</th>
      <th>状态</th>
      <th>操作</th>
    </tr>
    </thead>
    <tbody>
    </tbody>
  </table>
</div>
<div class="pagination">
  <span>共0条</span>
  <select class="data-table-page">
    <option value="10" selected>10条/页</option>
    <option value="20">20条/页</option>
    <option value="50">50条/页</option>
  </select>
  <div class="page-num">
    <button class="pre-button">＜</button>
    <span>1</span>
    <button class="next-button">＞</button>
  </div>
</div>

<!-- 新增弹窗 -->
<div class="modal-mask" id="modal-mask-add">
  <div class="modal-content">
    <h3 class="modal-title">
      新增品牌型号
      <button class="modal-close-btn">×</button>
    </h3>
    <form class="modal-form" id="modal-form-add">
      <div class="form-item">
        <label>品牌名称：</label>
        <select id="add-brandId" required>
          <option value="">请选择品牌</option>
        </select>
      </div>
      <div class="form-item">
        <label>型号名称：</label>
        <input type="text" id="add-model" placeholder="请输入型号名称" required>
      </div>
      <div class="form-item">
        <label>配置：</label>
        <input type="text" id="add-config" placeholder="请输入配置" required>
      </div>
      <div class="form-item">
        <label>重量(t)：</label>
        <input type="number" id="add-weight" placeholder="请输入重量" required>
      </div>
      <div class="form-item">
        <label>长(m)：</label>
        <input type="number" id="add-length" placeholder="请输入长度" required>
      </div>
      <div class="form-item">
        <label>宽(m)：</label>
        <input type="number" id="add-width" placeholder="请输入宽度" required>
      </div>
      <div class="form-item">
        <label>高(m)：</label>
        <input type="number" id="add-height" placeholder="请输入高度" required>
      </div>
      <div class="form-item">
        <label>是否新能源：</label>
        <select id="add-isNewEnergy" required>
          <option value="1">是</option>
          <option value="0">否</option>
        </select>
      </div>
      <div class="modal-buttons">
        <button type="button" class="btn-close">关闭</button>
        <button type="submit" class="btn-submit">确定</button>
      </div>
    </form>
  </div>
</div>

<!-- 修改弹窗 -->
<div class="modal-mask" id="modal-mask-update">
  <div class="modal-content">
    <h3 class="modal-title">
      修改品牌型号
      <button class="modal-close-btn">×</button>
    </h3>
    <form class="modal-form" id="modal-form-update">
      <div class="form-item">
        <label>品牌名称：</label>
        <select id="update-brandId" required>
          <option value="">请选择品牌</option>
        </select>
      </div>
      <div class="form-item">
        <label>型号名称：</label>
        <input type="text" id="update-model" required>
      </div>
      <div class="form-item">
        <label>配置：</label>
        <input type="text" id="update-config" required>
      </div>
      <div class="form-item">
        <label>重量(t)：</label>
        <input type="number" id="update-weight" required>
      </div>
      <div class="form-item">
        <label>长(m)：</label>
        <input type="number" id="update-length" required>
      </div>
      <div class="form-item">
        <label>宽(m)：</label>
        <input type="number" id="update-width" required>
      </div>
      <div class="form-item">
        <label>高(m)：</label>
        <input type="number" id="update-height" required>
      </div>
      <div class="form-item">
        <label>是否新能源：</label>
        <select id="update-isNewEnergy" required>
          <option value="1">是</option>
          <option value="0">否</option>
        </select>
      </div>
      <div class="modal-buttons">
        <button type="button" class="btn-close">关闭</button>
        <button type="submit" class="btn-submit">保存</button>
      </div>
    </form>
  </div>
</div>

<!-- 详情弹窗 -->
<div class="modal-mask" id="modal-mask-detail">
  <div class="modal-content">
    <h3 class="modal-title">
      品牌型号详情
      <button class="modal-close-btn">×</button>
    </h3>
    <div class="detail-section">
      <div class="detail-row">
        <span class="detail-label">品牌名称：</span>
        <span class="detail-value" id="detail-brandName"></span>
      </div>
      <div class="detail-row">
        <span class="detail-label">型号名称：</span>
        <span class="detail-value" id="detail-model"></span>
      </div>
      <div class="detail-row">
        <span class="detail-label">配置：</span>
        <span class="detail-value" id="detail-config"></span>
      </div>
      <div class="detail-row">
        <span class="detail-label">重量：</span>
        <span class="detail-value" id="detail-weight"></span>
      </div>
      <div class="detail-row">
        <span class="detail-label">长x宽x高：</span>
        <span class="detail-value" id="detail-dimensions"></span>
      </div>
      <div class="detail-row">
        <span class="detail-label">是否新能源：</span>
        <span class="detail-value" id="detail-isNewEnergy"></span>
      </div>
      <div class="detail-row">
        <span class="detail-label">状态：</span>
        <span class="detail-value" id="detail-status"></span>
      </div>
    </div>
    <div class="modal-buttons">
      <button type="button" class="btn-close">关闭</button>
    </div>
  </div>
</div>

<script>
  const nextButton = document.querySelector('.next-button');
  const preButton = document.querySelector('.pre-button');

  // 渲染表格数据
  function renderTable(data) {
    document.querySelector('.pagination span:first-child')
            .textContent = `共${data.data.total}条`;
    const tbody = document.querySelector('.data-table tbody');

    // 更新页码显示
    document.querySelector('.page-num span').textContent = data.data.current;

    // 处理分页按钮状态
    if (data.data.current >= data.data.pages) {
      nextButton.disabled = true;
      nextButton.style.opacity = "0.5";
    } else {
      nextButton.disabled = false;
      nextButton.style.opacity = "1";
    }

    if (data.data.current <= 1) {
      preButton.disabled = true;
      preButton.style.opacity = "0.5";
    } else {
      preButton.disabled = false;
      preButton.style.opacity = "1";
    }

    tbody.innerHTML = ''; // 清空旧数据
    data.data.records. slice( // 根据分页参数切割数据
            (data.data.current - 1)
            * data.data.size,
            data.data.current * data.data.size
    ).forEach((item, index) => {
      const tr = document.createElement('tr');
      const status = item.status === 1 ? '启用中' : '停用';
      const isNewEnergy = item.isNewEnergy === 1 ? '是' : '否';
      const dimensions = `${item.length}x${item.width}x${item.height}`;

      tr.innerHTML = `
                <td>${(data.data.current - 1) * data.data.size + index + 1}</td>
                <td>${item.brandName || ''}</td>
                <td>${item.model || ''}</td>
                <td>${item.config || ''}</td>
                <td>${item.weight || ''}</td>
                <td>${dimensions}</td>
                <td>${isNewEnergy}</td>
                <td>${status}</td>
                <td>
                    <button class="table-detail-btn" )">详情</button>
                    <button class="table-edit-btn" )">修改</button>
                </td>
            `;
      // 设置tr的data-id属性
      tr.dataset.id = item.id;
      const detailBtn = tr.querySelector('.table-detail-btn');
      // const disableBtn = tr.querySelector('.table-disable-btn');
      const editBtn = tr.querySelector('.table-edit-btn');
      // detailBtn.addEventListener('click', () => showCustomerDetail(item));
      // editBtn.addEventListener('click', () => showUpdateModal(item.id));
      detailBtn.addEventListener('click',() =>showDetail(item.id));
      editBtn.addEventListener('click',() =>showUpdateModal(item.id));

      tbody.appendChild(tr);
    });
  }

  // 查询按钮事件
  document.querySelector('.btn-query').addEventListener('click', () => {
    fetchData('query');
  });

  // 重置按钮事件
  document.querySelector('.btn-reset').addEventListener('click', () => {
    document.querySelectorAll('.form-input').forEach(input => {
      if (input.type === 'text') input.value = '';
      if (input.tagName === 'SELECT') input.value = '';
    });
  });

  // 新增按钮事件
  document.querySelector('.btn-add').addEventListener('click', () => {
    loadBrands().then(() => {
      document.querySelector('#modal-mask-add').style.display = 'flex';
    });
  });

  // 关闭弹窗
  document.querySelectorAll('.modal-close-btn, .btn-close').forEach(btn => {
    btn.addEventListener('click', function() {
      this.closest('.modal-mask').style.display = 'none';
    });
  });

  // 获取分页参数
  function getPaginationParams() {
    return {
      page: Math.max(1, parseInt(document.querySelector('.page-num span').textContent)),
      pageSize: parseInt(document.querySelector('.data-table-page').value)
    };
  }

  // 分页按钮事件
  document.querySelector('.pre-button').addEventListener('click', () => {
    fetchData('pre');
  });

  document.querySelector('.next-button').addEventListener('click', () => {
    fetchData('next');
  });

  // 数据请求函数
  async function fetchData(type) {
    let { page, pageSize } = getPaginationParams();

    if (type === 'pre') {
      page = Math.max(1, page - 1);
    } else if (type === 'next') {
      page += 1;
    }

    const queryParams = {
      brandName: document.querySelector('input[placeholder="请输入品牌名称"]').value,
      model: document.querySelector('input[placeholder="请输入型号"]').value,
      isNewEnergy: document.querySelector('.form-select-energy').value,
      status: document.querySelector('.form-select-status').value,
      page: page,
      rows: pageSize
    };

    try {
      const response = await fetch('http://localhost:8080/sys/customerCarModel/pageList', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(queryParams)
      });

      const data = await response.json();
      if (data.status === 0) {
        renderTable(data);
      } else {
        console.error('请求失败:', data.message);
      }
    } catch (error) {
      console.error('请求失败:', error);
    }
  }

  // 加载品牌列表
  async function loadBrands() {
    try {
      const response = await fetch('http://localhost:8080/sys/customerBrand/selectAllBrand', {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' }
      });

      const data = await response.json();
      if (data.status === 0) {
        const brands = data.data;
        const addSelect = document.getElementById('add-brandId');
        const updateSelect = document.getElementById('update-brandId');

        // 清空现有选项
        addSelect.innerHTML = '<option value="">请选择品牌</option>';
        updateSelect.innerHTML = '<option value="">请选择品牌</option>';

        // 添加新选项
        brands.forEach(brand => {
          const option = `<option value="${brand.id}">${brand.brand}</option>`;
          addSelect.insertAdjacentHTML('beforeend', option);
          updateSelect.insertAdjacentHTML('beforeend', option);
        });
      }
    } catch (error) {
      console.error('加载品牌列表失败:', error);
    }
  }

  // 显示详情
  async function showDetail(id) {
    try {
      const response = await fetch(`http://localhost:8080/sys/customerCarModel/detail/${id}`, {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' }
      });

      const data = await response.json();
      if (data.status === 0) {
        const detail = data.data;
        document.getElementById('detail-brandName').textContent = detail.brandName;
        document.getElementById('detail-model').textContent = detail.model;
        document.getElementById('detail-config').textContent = detail.config;
        document.getElementById('detail-weight').textContent = detail.weight;
        document.getElementById('detail-dimensions').textContent = 
          `${detail.length}x${detail.width}x${detail.height}`;
        document.getElementById('detail-isNewEnergy').textContent = 
          detail.isNewEnergy === 1 ? '是' : '否';
        document.getElementById('detail-status').textContent = 
          detail.status === 1 ? '启用中' : '停用';

        document.getElementById('modal-mask-detail').style.display = 'flex';
      }
    } catch (error) {
      console.error('加载详情失败:', error);
    }
  }

  // 显示修改弹窗
  async function showUpdateModal(id) {
    try {
      // await loadBrands();
      const response = await fetch(`http://localhost:8080/sys/customerCarModel/detail/${id}`, {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' }
      });

      const data = await response.json();
      if (data.status === 0) {
        const detail = data.data;
        document.getElementById('update-brandId').value = detail.brandId;
        document.getElementById('update-model').value = detail.model;
        document.getElementById('update-config').value = detail.config;
        document.getElementById('update-weight').value = detail.weight;
        document.getElementById('update-length').value = detail.length;
        document.getElementById('update-width').value = detail.width;
        document.getElementById('update-height').value = detail.height;
        document.getElementById('update-isNewEnergy').value = detail.isNewEnergy;

        const modal = document.getElementById('modal-mask-update');
        modal.dataset.currentId = id;
        modal.style.display = 'flex';
      }
    } catch (error) {
      console.error('加载详情失败:', error);
    }
  }

  // 新增表单提交
  document.getElementById('modal-form-add').addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const formData = {
        brandId: document.getElementById('add-brandId').value,
        model: document.getElementById('add-model').value,
        config: document.getElementById('add-config').value,
        weight: parseFloat(document.getElementById('add-weight').value),
        length: parseFloat(document.getElementById('add-length').value),
        width: parseFloat(document.getElementById('add-width').value),
        height: parseFloat(document.getElementById('add-height').value),
        isNewEnergy: parseInt(document.getElementById('add-isNewEnergy').value)
    };

    try {
        const response = await fetch('http://localhost:8080/sys/customerCarModel/add', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(formData)
        });

        const data = await response.json();
        if (data.status === 0) {
            alert('添加成功');
            document.getElementById('modal-mask-add').style.display = 'none';
            document.getElementById('modal-form-add').reset();
            fetchData('query');
        } else {
            alert('添加失败：' + (data.message || '未知错误'));
        }
    } catch (error) {
        console.error('提交失败:', error);
        alert('提交失败：' + error.message);
    }
  });

  // 修改表单提交
  document.getElementById('modal-form-update').addEventListener('submit', async (e) => {
    e.preventDefault();
    const modal = document.getElementById('modal-mask-update');
    const formData = {
      id: modal.dataset.currentId,
      brandId: document.getElementById('update-brandId').value,
      model: document.getElementById('update-model').value,
      config: document.getElementById('update-config').value,
      weight: parseFloat(document.getElementById('update-weight').value),
      length: parseFloat(document.getElementById('update-length').value),
      width: parseFloat(document.getElementById('update-width').value),
      height: parseFloat(document.getElementById('update-height').value),
      isNewEnergy: parseInt(document.getElementById('update-isNewEnergy').value)
    };

    try {
      const response = await fetch('http://localhost:8080/sys/customerCarModel/update', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData)
      });

      const data = await response.json();
      if (data.status === 0) {
        alert('修改成功');
        modal.style.display = 'none';
        fetchData('query');
      } else {
        alert('修改失败：' + data.message);
      }
    } catch (error) {
      console.error('提交失败:', error);
      alert('提交失败：' + error.message);
    }
  });
  
    loadBrands(); // 加载品牌列表

  // 页面加载完成后执行初始查询和加载品牌列表
  document.addEventListener('DOMContentLoaded', () => {
    fetchData('query');
    loadBrands(); // 加载品牌列表
  });
</script>
</body>
</html>